<template>
  <!-- 添加或修改销售信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择项目" filterable clearable
                           style="width: 300px">
                  <el-option v-for="dict in PrjNameOptions"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <!--<el-col :span="12">
            <el-form-item label="销售人" prop="saleId">
              <el-select v-model="form.saleId" placeholder="请选择采购人" @change="selectUser" clearable style="width: 300px">
                <el-option v-for="dict in dict.type.sys_user" ref="myselectUser"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">-->
            <el-col :span="12">
              <el-form-item label="销售日期" prop="saleDate">
                <el-date-picker clearable
                                v-model="form.saleDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择销售日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="备注信息" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息"/>
              </el-form-item>
            </el-col>

          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <el-col :span="1.5">
      <el-button type="primary" plain icon="el-icon-plus" size="mini"  @click="handleAddList" >增加商品</el-button>
    </el-col>

    <el-table border v-loading="loading" ref="dragTable" :data="columns" row-key="id">
<!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="商品品牌" align="center" prop="brand"/>
      <el-table-column label="商品型号" align="center" prop="model"/>
      <el-table-column label="商品单位" align="center" prop="unit"/>
<!--      <el-table-column label="采购单价" align="center" prop="costPrice"/>-->
      <el-table-column label="含税单价" align="center" prop="costPriceTax"/>
      <!--<el-table-column label="采购数量" align="center" prop="count"/>
      <el-table-column label="含税总价" align="center" prop="costTax"/>-->
      <el-table-column label="库存数量" align="center" prop="remainderCount"/>
      <el-table-column label="销售价格" align="center" width="210">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.goodsUnitPrice" :precision="2" :min="0"
                           @change="handleChangeMoney(scope.row)"></el-input-number><!--scope.row.costPriceTax/2-->
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" width="210">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.goodsCount" :max="scope.row.remainderCount" :min="0"
                           @change="handleChangeMoney(scope.row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="销售总价" align="center" width="210">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.goodsTotalPrice" :min="0" disabled></el-input-number>
        </template>
      </el-table-column>
      <!--<el-table-column label="销售时间" align="center" width="170">
        <template slot-scope="scope">
          <el-date-picker clearable style="width: 160px;"
                          v-model="scope.row.buyDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择销售日期">
          </el-date-picker>
        </template>
      </el-table-column>-->

      <!--<el-table-column label="采购人姓名" align="center" prop="buyName"/>
      <el-table-column label="采购日期" align="center" prop="buyDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.buyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-popconfirm :title="`确认移除当前数据项？`" @confirm="handleRemove(scope.row)" style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete" >
              移除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- <goods-customer-chose ref="goodsCustomerChose" @ok="getList"></goods-customer-chose>-->
    <goods-order-in-list-select-for-sale ref="GoodsOrderInListSelectForSale" @ok="updateOrderList"></goods-order-in-list-select-for-sale>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>

</template>


<script>
    import {addAction, getAction, getById, deleteAction, updateAction} from '@/api/manage'
    // import GoodsCustomerChose from "./GoodsCustomerChose";
    import {updateGoodsSale} from '@/api/develop/goodsSale'
    import request from '@/utils/request'
    import GoodsOrderInListSelectForSale from "../../goodsOrderIn/GoodsOrderInListSelectForSale";

    export default {
        name: "GoodsSaleBatchForPrj",
        components: {
            // GoodsCustomerChose,
            GoodsOrderInListSelectForSale
        },
        dicts: ['goods_supplier'],
        data() {
            return {
                // 遮罩层
                loading: true,
                activeName: "first",
                // 弹出层标题
                title: "批量销售",
                // 是否显示弹出层
                open: false,
                // 表单参数
                form: {},
                columns: [],
                dataList: [],
                total: 0,
                selectIds: [],
                selectIdsNew: [],
                // 表单校验
                rules: {
                    projectId: [
                        {required: true, message: "项目不能为空", trigger: "blur"}
                    ],
                    /*customerId: [
                        {required: true, message: "客户不能为空", trigger: "blur"}
                    ],*/
                    /*saleId: [
                        {required: true, message: "销售人不能为空", trigger: "blur"}
                    ],*/
                    saleDate: [
                        {required: true, message: "销售日期不能为空", trigger: "blur"}
                    ],
                },
                queryParams: {
                    pageNum: 1,
                    pageSize: 20,
                    id: null,
                    name: null,
                    taxNo: null,
                    addr: null,
                    tel: null,
                    bankName: null,
                    bankNo: null,
                    info: null,
                    status: "0",
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    remark: null
                },
                url: {
                    listBatch: '/goodsOrderIn/goodsOrderIn/listBatch/',
                    getById: '/goodsSale/goodsSale/',
                    add: '/goodsSale/goodsSale/add',
                    addBatch: '/goodsSale/goodsSale/addBatch',
                    edit: '/goodsSale/goodsSale/edit',
                    insertBatch: '/goodsSale/goodsSale/insertBatch',
                    prjNames: '/projectBaseInfo/projectBaseInfo/prjNames',
                },
                orderInfo: {},
                PrjNameOptions:[],
                saleType: "",
            };
        },
        created() {

        },
        methods: {
            intDictsForPrj(){
                let that = this;
                getAction( that.url.prjNames, {} ).then(res => {
                    that.PrjNameOptions = res.data.nameList;
                })
            },
            handleRemove(row){
                let that = this;
                that.columns = that.columns.filter((item) => {
                    return item.id != row.id
                });
                that.form.columns = that.columns;
                that.selectIdsNew = [];
                for (let i = 0; i < that.columns.length; i++) {
                    let row = that.columns[i];
                    that.selectIdsNew.push(row.id);
                }
                that.selectIds = that.selectIdsNew;
                that.$modal.msgSuccess("移除成功！");
            },
            updateOrderList(selectRows) {
                let that = this;
                let orderIds = that.selectIds;
                for (let i = 0; i < selectRows.length; i++) {
                    let row = selectRows[i];
                    // row.buyDate = new Date();
                    that.columns.push(row);
                }
                for (let i = 0; i < that.columns.length; i++) {
                    let row = that.columns[i];
                    that.selectIdsNew.push(row.id);
                }
                that.selectIds = that.selectIdsNew;
            },
            handleAddList(){
                let that = this;
                that.$refs.GoodsOrderInListSelectForSale.showSelectOrderDialog(that.selectIds);
            },
            handleChangeMoney(row) {
                let that = this;
                let handleReckonMoney = (row) => {
                    let row_money = 0;
                    row_money = that.functionNumberMul(Number(row.goodsUnitPrice), Number(row.goodsCount))
                    that.$set(row, 'goodsTotalPrice', row_money);
                };
                handleReckonMoney(row);
            },

            /*updateTotlePrice() {
                let that = this;
                if (that.form.goodsCount && that.form.goodsUnitPrice) {
                    let totlePrice = that.functionNumberMul(that.form.goodsCount, that.form.goodsUnitPrice);
                    that.$set(that.form, "goodsTotalPrice", totlePrice);
                }
            },*/
            functionNumberMul(arg1, arg2) {
                var m = 0;
                var s1 = arg1.toString();
                var s2 = arg2.toString();
                try {
                    m += s1.split(".")[1].length;
                } catch (e) {
                }
                try {
                    m += s2.split(".")[1].length;
                } catch (e) {
                }
                return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
            },
            show(idss, type) {
                let that = this;
                that.saleType = type;
                that.reset();
                that.columns = [];
                that.selectIds = idss;
                that.open = true;
                that.form.saleDate = new Date();
                that.getList();
                that.intDictsForPrj();
            },
            saleGoods(type) {
                let that = this;
                that.saleType = type;
                that.reset();
                that.open = true;
                that.form.saleDate = new Date();
                that.intDictsForPrj();
                that.loading = false;
            },
            /*choseCustomer() {
                this.$refs.goodsCustomerChose.show();
            },*/
            getList() {
                this.loading = true;
                getById(this.url.listBatch, this.selectIds).then(response => {
                    this.columns = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            selectCustomer(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectCustomer;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.customerName = arr[i].label;
                        }
                    }
                })
            },
            selectSupplier(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectSsupplier;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.supplierName = arr[i].label;
                        }
                    }
                })
            },
            /*selectUser(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectUser;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.saleName = arr[i].label;
                        }
                    }
                })
            },*/
            /*sale(row) {
                let that = this;
                that.open = true;
                that.title = "销售";
                that.orderInfo = row;
                that.form.goodsName = row.name;
                that.form.goodsBrand = row.brand;
                that.form.goodsCount = row.count;
                that.form.supplierId = row.supplierId;
                that.form.supplierName = row.supplierName;
                that.form.saleId = that.$store.getters.userId;
                that.form.saleName = that.$store.getters.nickName;
                that.form.saleDate = new Date();
                /!*console.log(that.$store.state.user.userId);
                console.log(that.$store.state.user.nickName);*!/
            },*/
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    goodsId: null,
                    goodsName: null,
                    goodsBrand: null,
                    goodsUnitPrice: null,
                    goodsCount: null,
                    goodsTotalPrice: null,
                    saleDate: new Date(),
                    supplierId: null,
                    supplierName: null,
                    customerId: null,
                    customerName: null,
                    invoice: "0",
                    invoiceId: null,
                    invoiceNo: null,
                    fundCallback: "0",
                    receipt: null,
                    saleId: null,
                    saleName: null,
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    remark: null,
                    deptId: this.$store.getters.deptId,
                    deptName: this.$store.getters.deptName,
                };
                this.selectIds = [];
                this.columns = [];
                this.resetForm("form");
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加销售信息管理";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id = row.id || this.selectIds;
                getById(this.url.getById, id).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "修改销售信息管理";
                });
            },
            /** 提交按钮 */
            submitForm() {
                let that = this;
                that.$refs["form"].validate(valid => {
                    if (valid) {
                        const goodsSaleForm = that.form;
                        const goodsOrderIn = Object.assign({}, goodsSaleForm);
                        goodsOrderIn.columns = that.columns;
                        goodsOrderIn.form = goodsSaleForm;
                        goodsOrderIn.type = that.saleType;//项目销售:2/项目费用:3(零散销售:1)
                        goodsOrderIn.saleId = that.$store.getters.userId;
                        goodsOrderIn.saleName = that.$store.getters.nickName;
                        addAction(that.url.insertBatch, goodsOrderIn).then(response => {
                          that.$modal.msgSuccess("销售成功");
                          that.open = false;
                          that.$emit('ok');
                        });
                       /* updateGoodsSale(goodsOrderIn).then(res => {
                            that.$modal.msgSuccess(res.msg);
                            if (res.code === 200) {
                                that.$modal.msgSuccess("销售完成！");
                                this.open = false;
                                that.$emit('ok');
                            }
                        });*/
                    }
                });
            },
        }
    };
</script>
